package com.lonty.intelligence.service;

import com.lonty.intelligence.api.Result;
import com.lonty.intelligence.api.ResultCode;
import com.lonty.intelligence.mapper.HouseholdManagementMapper;
import com.lonty.intelligence.model.HouseholdManagement;
import com.lonty.intelligence.util.RedisUtil;
import com.lonty.intelligence.util.UUIDUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * @Author 陈璇
 * @Date 2020/4/23 9:50
 * @Version 1.0
 */
@Service
public class HouseholdManagementService {

    @Resource
    private HouseholdManagementMapper householdManagementMapper;

    /**
     * 保存住户管理
     * @param telephone
     * @return
     */
    public HouseholdManagement saveHouseholdManagement(String telephone){
        HouseholdManagement householdManagement = new HouseholdManagement();
        householdManagement.setTelephone(telephone);
        householdManagement.setPassword(UUIDUtil.randomID());
        householdManagement.setToken(UUIDUtil.randomUUID());
        householdManagement.setIsDel(0);
        if(householdManagementMapper.saveHouseholdManagement(householdManagement) > 0){
            return householdManagement;
        }
        return null;
    }

    /**
     * 住户管理登录
     * @param phone
     * @param code
     * @return
     */
    public Result login(String phone, String code, String password){
        String verificationCode = (String) RedisUtil.get(phone);
        HouseholdManagement householdManagement = householdManagementMapper.getByTelephone(phone);
        if(verificationCode == null){
            //验证码已过期
            return Result.builder(ResultCode.CODE_IS_OVERDUE).build();
        }
        //判断验证码是否正确
        if(!code.equals(verificationCode)){
            return Result.builder(ResultCode.CODE_IS_ERROR).build();
        }
        if(!householdManagement.getPassword().equals(password)){
            return Result.builder(ResultCode.PASSWORD_IS_ERROR).build();
        }
        return Result.builder().data(householdManagement).build();
    }

}
